package com.task.controller;

import com.google.common.collect.Maps;
import com.task.bean.Constants;
import com.task.bean.EnumConstants.ChildTaskStatus;
import com.task.bean.EnumConstants.TaskType;
import com.task.bean.ParentTaskBean;
import com.task.entity.ChildTask;
import com.task.entity.ParentTask;
import com.task.service.IChildTaskService;
import com.task.service.IParentTaskService;
import com.task.utils.PropertiesUtil;
import com.task.utils.TaskDomain;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.ServletRequest;
import java.util.*;

/**
 * 平台级别Controller
 *
 * @author wangmin
 */
@Controller
public class PlatformContoller {

    private static final Logger LOGGER = LoggerFactory.getLogger(PlatformContoller.class);

    @Autowired
    IChildTaskService childTaskService;

    @Autowired
    IParentTaskService parentTaskService;

    /**
     * 登录成功后系统首页
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/index.html")
    public String toIndex() {
        return "/index";
    }

    @RequestMapping(value = "/mobile.html")
    public String toMobile(ModelMap model, @RequestParam(value = "userId") String userId,
    		@RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime ) {
        try {
            Map<String, Object> searchParams = new HashMap<String, Object>();
            // 查询条件 状态 - [发布中]的子任务
            searchParams.put("EQ_status", ChildTaskStatus.PUBLISH);
            if(StringUtils.isNotBlank(startTime)){
           	 searchParams.put("GTE_parentTask.startTime", startTime);
            }
            if(StringUtils.isNotBlank(endTime)){
          	 searchParams.put("LTE_parentTask.endTime", endTime);
            }
            Page<ChildTask> page = childTaskService.findChildList(searchParams, 1, 10, Constants.DESC, Constants.ID);
            if (page != null && CollectionUtils.isNotEmpty(page.getContent())) {
                List<TaskDomain> taskList = new ArrayList<TaskDomain>();

                for (ChildTask child : page.getContent()) {
                    TaskDomain domain = new TaskDomain();
                    ParentTask pt = parentTaskService.findById(child.getParentTaskId());
                    if (null != pt) {
                        domain.setTaskName(pt.getTaskName());
                        domain.setEndDate(pt.getEndTime());
                        domain.setStartDate(pt.getStartTime());
                        domain.setTaskType(pt.getTaskType().getMsg());
                        if (pt.getReward() != null) {
                            domain.setMoney("¥" + pt.getReward());
                        } else {
                            domain.setMoney(Constants.FREE);
                        }
                    }
                    domain.setId(child.getId().toString());
                    domain.setStoreAddress(child.getStore().getStoreAddress());
                    domain.setStoreCode(child.getStoreCode());
                    domain.setStoreName(child.getStore().getStoreName());
                    domain.setCode(child.getCode());
                    taskList.add(domain);
                }
                model.addAttribute("taskList", taskList);
            }
        } catch (Exception e) {
            LOGGER.error("find task page error:{}", e);
        }
        model.addAttribute("userId", userId);
        return "/mobile";
    }

    @RequestMapping(value = "/list.html")
    public String toMobileTaskList(ModelMap model, @RequestParam(value = "userId") String userId,
                                   @RequestParam(value = "taskType", required = false) String taskType ) {
        try {
            model.addAttribute("userId", userId);
            model.addAttribute("taskType", taskType);
            Map<String, Object> searchParams = new HashMap<String, Object>();
            // 查询条件 状态 - [发布中]的子任务
            searchParams.put("EQ_status", ChildTaskStatus.PUBLISH);
            if (StringUtils.isNotBlank(taskType)) {
                TaskType type = TaskType.DATA;
                if ("DATA".equals(taskType)) {
                    type = TaskType.DATA;
                } else if ("INVEST".equals(taskType)) {
                    type = TaskType.INVEST;
                } else if ("ARRANG".equals(taskType)) {
                    type = TaskType.ARRANG;
                } else {
                    type = TaskType.PROMOTION;
                }
                searchParams.put("EQ_parentTask.taskType", type);
            }
            Page<ChildTask> page = childTaskService.findChildList(searchParams, 1, 20, Constants.DESC, Constants.ID);
            if (page != null && CollectionUtils.isNotEmpty(page.getContent())) {
                List<TaskDomain> taskList = new ArrayList<TaskDomain>();

                for (ChildTask child : page.getContent()) {
                    TaskDomain domain = new TaskDomain();
                    ParentTask pt = parentTaskService.findById(child.getParentTaskId());
                    if (null != pt) {
                        domain.setTaskName(pt.getTaskName());
                        domain.setEndDate(pt.getEndTime());
                        domain.setStartDate(pt.getStartTime());
                        domain.setTaskType(pt.getTaskType().getMsg());
                        domain.setMoney(pt.getReward().toString());
                    }
                    domain.setId(child.getId().toString());
                    domain.setStoreAddress(child.getStore().getStoreAddress());
                    domain.setStoreCode(child.getStoreCode());
                    domain.setStoreName(child.getStore().getStoreName());
                    domain.setCode(child.getCode());
                    taskList.add(domain);
                }
                model.addAttribute("taskList", taskList);
            }
        } catch (Exception e) {
            LOGGER.error("find task page error:{}", e);
        }
        return "/mobile/list";
    }

    @PersistenceContext
    private EntityManager entityManager;

    /**
     * <查询任务列表[前十条]>
     *
     * @param offset
     * @param limit
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list.json")
    public JSONObject findMyTaskList(@RequestParam(value = "taskType", required = false) String taskType,
                                     @RequestParam(value = "taskName", required = false) String taskName,
                                     @RequestParam(value = "userId", required = true) String userId,
                                     @RequestParam(value = "orderDirection", defaultValue = Constants.DESC) String orderDirection,
                                     @RequestParam(value = "orderField", defaultValue = Constants.ID) String orderField,
                                     @RequestParam(value = "offset", defaultValue = Constants.DEFAULT_PAGE) int offset,
                                     @RequestParam(value = "limit", defaultValue = "10") int limit,  
                                     @RequestParam(value = "startTime", required = false) String startTime,
                                     @RequestParam(value = "endTime", required = false) String endTime,ServletRequest request,
                                     @RequestParam(value = "longitude", required = false) String longitude,
                                     @RequestParam(value = "latitude", required = false) String latitude) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(Constants.ROWS, new ArrayList<ParentTaskBean>());
        jsonObject.put(Constants.TOTAL, 0);

        /**计算距离的公式start**/
      /*  String distance=",ROUND(6378.138*2*ASIN(SQRT(POW(SIN(("+latitude+"*PI()/180-tufa_store.latitude*PI()/180)/2),2)+COS("+latitude+"*PI()/180)*COS(tufa_store.latitude*PI()/180)*" +
                "POW(SIN(("+longitude+"*PI()/180-tufa_store.longitude*PI()/180)/2),2)))*1000)  as compareLocation";*/
        /**计算距离的公式end**/

        /***
         * 下面是使用原始sql查询按距离排序
         */
        String sql="select tufa_child_task.id from tufa_child_task,tufa_store,tufa_parent_task where tufa_child_task.store_code=tufa_store.store_code and" +
                " tufa_child_task.parent_task_id=tufa_parent_task.id and tufa_child_task.status='PUBLISH' ";

       try {
            int pageNum = offset / limit + 1;
            Map<String, Object> searchParams = new HashMap<String, Object>();
            // 查询条件 状态 - [发布中]的子任务
            searchParams.put("EQ_status", ChildTaskStatus.PUBLISH);
            if(StringUtils.isNotBlank(startTime)){
            	 searchParams.put("GTE_parentTask.startTime", startTime);
                sql+=" and tufa_parent_task.start_time<='"+startTime+"'";
            }else{
                sql+=" and tufa_parent_task.start_time<=NOW() ";
            }
            if(StringUtils.isNotBlank(endTime)){
           	 searchParams.put("LTE_parentTask.endTime", endTime);
                sql+=" and tufa_parent_task.end_time>='"+endTime+"'";
            }else{
                sql+=" and tufa_parent_task.end_time>NOW() ";
            }
            if (StringUtils.isNotBlank(taskType)) {
                TaskType type = TaskType.DATA;
                if ("DATA".equals(taskType)) {
                    type = TaskType.DATA;
                } else if ("INVEST".equals(taskType)) {
                    type = TaskType.INVEST;
                } else if ("ARRANG".equals(taskType)) {
                    type = TaskType.ARRANG;
                } else {
                    type = TaskType.PROMOTION;
                }
                searchParams.put("EQ_parentTask.taskType", type);
                sql+=" and tufa_parent_task.task_type ='"+type+"'";
            }
            if (StringUtils.isNotBlank(taskName)) {
                searchParams.put("LIKE_parentTask.taskName", taskName);
                sql+=" and tufa_parent_task.task_name like '%"+taskName+"%'";
            }
        //   searchParams.put("EQ_store.storeCode", "0010-0010");//根据门店条件查询
         if(orderField!=null&&orderField.equals("bynear")) {
             if(null!=longitude&&null!=latitude&&!"".equals(longitude.trim())&&!"".equals(latitude.trim())) {
                 Query total = entityManager.createNativeQuery(sql);
                 orderField = "(tufa_store.longitude-" + longitude + ")*(tufa_store.longitude-" + longitude + ")+" +
                         "(tufa_store.latitude-" + latitude + ")*(tufa_store.latitude-" + latitude + ")  " + orderDirection +
                         " limit " + limit * (pageNum - 1) + " , " + limit;

                 sql += " order by " + orderField;
                 System.out.println(sql);
                 Query chirldIDs = entityManager.createNativeQuery(sql);
                 ChildTask child = null;
                 List<TaskDomain> taskList = new ArrayList<TaskDomain>();
                 for (Object objects : chirldIDs.getResultList()) {
                     //  Object[] cells = (Object[]) objects;
                     child = childTaskService.findById(Long.parseLong(objects.toString()));

                     TaskDomain domain = new TaskDomain();
                     ParentTask pt = parentTaskService.findById(child.getParentTaskId());
                     if (null != pt) {
                         domain.setTaskName(pt.getTaskName());
                         domain.setEndDate(pt.getEndTime());
                         domain.setStartDate(pt.getStartTime());
                         domain.setTaskType(pt.getTaskType().getMsg());
                     }
                     domain.setId(child.getId().toString());
                     domain.setStoreAddress(child.getStore().getStoreAddress());
                     domain.setStoreCode(child.getStoreCode());
                     domain.setStoreName(child.getStore().getStoreName());
                     domain.setCode(child.getCode());
                     if (null != child.getReward()) {
                         domain.setMoney("¥" + child.getReward());
                     } else {
                         domain.setMoney(Constants.FREE);
                     }
                     taskList.add(domain);
                 }
                 jsonObject.put(Constants.ROWS, taskList);
                 jsonObject.put(Constants.TOTAL, total.getResultList().size());
             }else{
                 jsonObject.put(Constants.ROWS, null);
                 jsonObject.put(Constants.TOTAL, 0);
             }
          }else {
             Page<ChildTask> page = childTaskService.findChildList(searchParams, pageNum, limit, orderDirection,
                     orderField);


             if (page != null && CollectionUtils.isNotEmpty(page.getContent())) {
                 List<TaskDomain> taskList = new ArrayList<TaskDomain>();

                 for (ChildTask child : page.getContent()) {
                     TaskDomain domain = new TaskDomain();
                         ParentTask pt = parentTaskService.findById(child.getParentTaskId());
                         if (null != pt) {
                             domain.setTaskName(pt.getTaskName());
                         domain.setEndDate(pt.getEndTime());
                         domain.setStartDate(pt.getStartTime());
                         domain.setTaskType(pt.getTaskType().getMsg());
                     }
                     domain.setId(child.getId().toString());
                     domain.setStoreAddress(child.getStore().getStoreAddress());
                     domain.setStoreCode(child.getStoreCode());
                     domain.setStoreName(child.getStore().getStoreName());
                     domain.setCode(child.getCode());
                     if (null != child.getReward()) {
                         domain.setMoney("¥" + child.getReward());
                     } else {
                         domain.setMoney(Constants.FREE);
                     }
                     taskList.add(domain);
                 }
                 jsonObject.put(Constants.ROWS, taskList);
                 jsonObject.put(Constants.TOTAL, page.getTotalElements());
             }
         }
        } catch (Exception e) {
            LOGGER.error("  findMyTaskList page error:{}", e);
        }
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/findWxConfig.json")
    public Map findWxConfig() {
        Map<String, String> map = Maps.newHashMap();
        Properties properties = PropertiesUtil.getProperties();
        for (Object key : properties.keySet()) {
            map.put((String) key, PropertiesUtil.getProperty((String) key));
        }
        return map;
    }
}
